﻿using Lanbt.Core.Entity.Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;

namespace Lanbt.Core.Web.Filter
{
    public class GlobalValidateFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                //处理包装ModelState
                List<string> modelStateErrors = new List<string>();
                foreach (var state in context.ModelState)
                {
                    string key = state.Key;
                    var errors = state.Value.Errors;
                    if (errors != null && errors.Count > 0)
                    {
                        List<string> errorMessages = errors.Select(error =>
                        {
                            return error.Exception != null ? error.Exception.Message : (String.IsNullOrEmpty(error.ErrorMessage) ? "An error has occurred " : error.ErrorMessage);
                        }).ToList();
                        if (errorMessages.Count() > 0)
                        {
                            modelStateErrors.AddRange(errorMessages);
                        }
                    }
                    if(modelStateErrors.Count() > 0)
                    {
                        ResultOutput<List<string>> response = new ResultOutput<List<string>>();
                        response.AddError("模型验证失败");
                        response.Result = modelStateErrors;
                        context.Result = new ObjectResult(response)
                        {
                            StatusCode = (int)HttpStatusCode.BadRequest,
                        };
                    }
                }
                //WriteEagleLog(null, context.HttpContext, EagleType.LOG_WARN, BizError.PARAMTER_VALIDATION_ERROR.ErrMessage);
            }
        }
    }
}
